<?php

namespace App\Admin\Controllers\Machine;

use App\Admin\Forms\ReplenishForm;
use App\Admin\Forms\ReplenishPriceForm;
use App\Admin\Repositories\SwtDheMachineGoods;
use App\Models\SwtMachine;
use App\Models\SwtMachineGood;
use App\Models\SwtReplenish;
use App\Models\SwtReplenishGoods;
use Dcat\Admin\Admin;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Card;

class SwtReplenishController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(SwtReplenish::with(['machine','merchant','administrator']), function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->column('id');
            $grid->column('machine.machine_name','设备名') -> display(function($value){
                return $value ?? '-';
            });
            $grid->column('merchant.name','机主') -> display(function($value){
                return $value ?? '<span class="text-danger">无机主</span>';
            });
            $grid->column('administrator.name','操作员') -> display(function($value){
                return $value ?? '<span class="text-danger">无</span>';
            });
            $grid->column('amount');
            $grid->column('status','状态')->using(['待补货','已完成','已取消'])->label(['info','success','danger']);
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid -> actions(function (Grid\Displayers\Actions $actions) {
               $actions -> disableView(false);
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
            });
        });
    }

    public function create(Content $content)
    {
        $machine_id = request()->get('machine_id');

        return $content
            ->translation($this->translation())
            ->title('进货单')
            ->body(function (Row $row) use ($machine_id){
                $row->column(6, $this->machineGoods($machine_id));
                $row->column(6, $this->replenishForm($machine_id));
            });
    }

    public function show($id, Content $content)
    {
        return $content
            ->translation($this->translation())
            ->title($this->title())
            ->description($this->description()['show'] ?? trans('admin.show'))
            ->body(function (Row $row) use ($id){
                $row->column(6, $this->detail($id));
                $row->column(6, $this->replenishGoods($id));
            });
    }

    public function machineGoods($machine_id)
    {
        $machine_info = SwtMachine::with('merchant_owner') -> find($machine_id);

        if($machine_info -> source_type == 2) {
            $grid = Grid::make( SwtMachineGood::with('goods') -> where('machine_id', $machine_id), function (Grid $grid) use($machine_info){
                if(count($machine_info -> merchant_owner) > 0) {
                    $url = admin_url('/machine/swt_machine');
                    $header = <<<HTML
<div class="btn-group pull-left" style="margin-right: 5px">
    <a href="{$url}" class="btn btn-sm btn-primary "><i class="feather icon-skip-back"></i><span class="d-none d-sm-inline">&nbsp;返回</span></a>
</div>
HTML;
                    $header .= "<div>机主：<span class='text-blue font-md-3'>{$machine_info -> merchant_owner[0]['name']}</span></div>";
                    $header .= "<div>剩余货款：<span class='text-red font-md-3'>{$machine_info -> merchant_owner[0]['pivot']['deposit_now']}</span></div>";
                    $grid->header($header);
                }
                $grid->column('id')->sortable();
                $grid->column('goods.goods_picture','商品图')->image('',60,60);
                $grid->column('goods.goods_name','商品名');
                $grid->column('weight','库存') -> display( function ($value) {
                    return $value > 0 ? "<span class='text-success'>{$value}</span>" : "<span class='text-danger'>{$value}</span>";
                });
                $grid->column('max_weight','最大库存');
                $grid->disableFilterButton();
                $grid->disableRefreshButton();
                $grid->disableActions();
            });
        } else {
            $grid = Grid::make( SwtDheMachineGoods::class, function (Grid $grid) use($machine_info){
                if(count($machine_info -> merchant_owner) > 0) {
                    $header = "<div>机主：<span class='text-blue font-md-3'>{$machine_info -> merchant_owner[0]['name']}</span></div>";
                    $header .= "<div>剩余货款：<span class='text-red font-md-3'>{$machine_info -> merchant_owner[0]['pivot']['deposit_now']}</span></div>";
                    $grid->header($header);
                }
                $grid -> model() ->filter() -> input('machine_id', $machine_info -> id);
                $grid->disablePagination();
                $grid->column('skuSubject','商品名');
                $grid->column('goodsStock','库存') -> display( function ($value) {
                    return $value > 0 ? "<span class='text-success'>{$value}</span>" : "<span class='text-danger'>{$value}</span>";
                });
                $grid->column('goodsPrice','售价');
                $grid->disableFilterButton();
                $grid->disableRefreshButton();
                $grid->disableActions();
            });
        }
        $card = Card::make($grid);
        return $card -> render();
    }

    public function replenishForm($machine_id)
    {
        $machine_info = SwtMachine::find($machine_id);
        if($machine_info -> source_type == 2) {
            $form = ReplenishForm::make()->payload(['id' => $machine_id]);
        } else {
            $form = ReplenishPriceForm::make()->payload(['id' => $machine_id]);
        }
        $card = Card::make('补货', $form);
        return $card->render();
    }


    protected function detail($id)
    {
        return Show::make($id, SwtReplenish::with(['merchant','machine','replenish_good']), function (Show $show) {
            $show->field('id');
            $show->field('machine.machine_no','设备号');
            $show->field('machine.machine_name','设备名');
            $show->field('merchant.name','商户名');
            $show->field('amount');
            $show->field('status','状态')->using(['待补货','已完成','已取消']);
            $show->field('created_at');
            $show->field('updated_at');
            $show->disableQuickEdit();
        });
    }

    public function replenishGoods($id)
    {
        $card = Card::make('商品列表',
            Grid::make(SwtReplenishGoods::where('replenish_id', $id), function (Grid $grid) {
                $grid->column('goods_name','商品名');
                $grid->column('cost_price','进货价');
                $grid->column('replenish_num','补货数量');
                $grid->column('amount','合计')->display( function() {
                    $amount = bcmul($this->replenish_num, $this->cost_price, 2);
                    if($amount > 0) {
                        return '<span class="text-success">¥'.$amount.'</span>';
                    } else {
                        return '<span class="text-danger">¥'.$amount.'</span>';
                    }
                });
                $grid->disableActions();
                $grid->disableRefreshButton();
            })
        );
        $btn = <<<HTML
        <button class="btn btn-sm btn-success" id="finishReplenish">完成</button>
        <button class="btn btn-sm btn-danger" id="cancelReplenish">取消</button>
HTML;

        $admin_id = Admin::user() -> id;

        Admin::script(<<<JS
        var id = {$id}
        var admin_id = {$admin_id}
        $("#finishReplenish").click(function(){
            Dcat.confirm('确定补货完成吗？', null, function () {

                $.post({
                    url: '/api/admin/replenish/finish',
                    data: {
                        id,
                        admin_id
                    },
                    success: function (res) {
                        if(!res.success) {
                            Dcat.error(res.message, null, {
                                timeOut: 5000
                            });
                        } else {
                            Dcat.success('操作成功', null, {
                                timeOut: 5000
                            });
                            Dcat.reload();
                        }
                    }
                });
            });
        })

        $("#cancelReplenish").click(function(){
            Dcat.confirm('确定取消补货吗？', null, function () {

                $.post({
                    url: '/api/admin/replenish/cancel',
                    data: {
                        id,
                        admin_id
                    },
                    success: function (res) {
                        if(!res.success) {
                            Dcat.error(res.message, null, {
                                timeOut: 5000
                            });
                        } else {
                            Dcat.success('操作成功', null, {
                                timeOut: 5000
                            });
                            Dcat.reload();
                        }
                    }
                });
            });
        })
JS);

        $replenish_info = SwtReplenish::find($id);

        if($replenish_info -> status == 0) {
            $card -> tool($btn);
        }

        return $card;
    }

}
